﻿

using EFCoreOptimisticCore;
using Microsoft.EntityFrameworkCore;

using var db = new SqlDbContext();

Console.WriteLine("输入名称：");
string userName = Console.ReadLine()!;
var house = await db.Houses.Where(p => p.Id == 1).SingleAsync();
if (string.IsNullOrEmpty(house.Owner))
{
    Console.WriteLine("开始抢...");
    house.Owner = userName;
    await Task.Delay(10000);
    try
    {
        db.SaveChanges();
    }
    catch(DbUpdateConcurrencyException e)
    {
       var entry = e.Entries.First();
       var dbValues = await entry.GetDatabaseValuesAsync();
       var ownerName = dbValues?.GetValue<string>(nameof(House.Owner));
       Console.WriteLine($"并发冲突，被{ownerName}提前抢走了");
    }

    Console.WriteLine("房子抢到手");
}
else
{
    if (house.Owner == userName)
    {
        Console.WriteLine("这个房子已经是你的了，不用抢");
    }
    else
    {
        Console.WriteLine($"这个房子已经被{house.Owner}抢走了");
    }
}

Console.ReadKey();